﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplicationC
{
    public partial class LoginSuccess : System.Web.UI.Page
    {
        public string cookieHost = ConfigHelper.CookieHost;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(Request.QueryString.Get("token")) &&
                !string.IsNullOrWhiteSpace(Request.QueryString.Get("userid")))
            {
                Session["userid"] = Request.QueryString.Get("userid");
                Session["token"] = Request.QueryString.Get("token");
            }
            else
            {
                Response.Redirect("~/login");
            }
        }

        protected void loginout_Click(object sender, EventArgs e)
        {
            string localhost = string.Format("http://{0}:{1}/", Request.Url.Host, Request.Url.Port);
            
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ConfigHelper.APIHost);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appliation/json"));
            UserInfo user = new UserInfo()
            {
                AppKey = ConfigHelper.AppKey,
                AppSecret = ConfigHelper.AppSecret,
                UserName = "km",
                Password = "123456",
                Ip = Request.UserHostAddress,
                UserId = Session["userid"]?.ToString(),
            };
            HttpResponseMessage response = client.PostAsJsonAsync("api/sso/loginout", user).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsAsync<Result>().Result;
                if (result?.Code == 0)
                {
                    
                    //清掉cookieHost的cookie
                    string returnUrlValue = Server.HtmlEncode(string.Format("{0}login?checkonline=true", localhost));
                    string returnUrl = string.Format("returnUrl={0}", returnUrlValue);
                    string userId = string.Format("userId={0}", Session["userid"]?.ToString());
                    string iframeUrl = ConfigHelper.CookieHost + "?";
                    string url = string.Format("{0}{1}&removeToken=true", iframeUrl, returnUrl);
                    string scriptBlock = string.Format(@"jQuery('#sso').attr('src','{0}')", url);
                    string script = "jQuery(function(){" + scriptBlock + "})";

                    Session.Clear();

                    ClientScript.RegisterStartupScript(this.GetType(), "iframe", script, true);
                }
                else
                {
                    Response.Write(string.Format("<script>alert('{0}')</script>", result?.Message));
                }

            }
        }
    }
}